home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / couchdb / json.py < prev    next >
Text File  |  2009-07-02  |  4KB  |  142 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # Copyright (C) 2009 Christopher Lenz
  5. # All rights reserved.
  6. #
  7. # This software is licensed as described in the file COPYING, which
  8. # you should have received as part of this distribution.
  9.  
  10. """Thin abstraction layer over the different available modules for decoding
  11. and encoding JSON data.
  12.  
  13. This module currently supports the following JSON modules:
  14.  - ``simplejson``: http://code.google.com/p/simplejson/
  15.  - ``cjson``: http://pypi.python.org/pypi/python-cjson
  16.  - ``json``: This is the version of ``simplejson`` that is bundled with the
  17.    Python standard library since version 2.6
  18.    (see http://docs.python.org/library/json.html)
  19.  
  20. The default behavior is to use ``simplejson`` if installed, and otherwise
  21. fallback to the standard library module. To explicitly tell CouchDB-Python
  22. which module to use, invoke the `use()` function with the module name::
  23.  
  24.     from couchdb import json
  25.     json.use('cjson')
  26.  
  27. In addition to choosing one of the above modules, you can also configure
  28. CouchDB-Python to use custom decoding and encoding functions::
  29.  
  30.     from couchdb import json
  31.     json.use(decode=my_decode, encode=my_encode)
  32.  
  33. """
  34.  
  35. __all__ = ['decode', 'encode', 'use']
  36.  
  37. _initialized = False
  38. _using = None
  39. _decode = None
  40. _encode = None
  41.  
  42.  
  43. def decode(string):
  44.     """Decode the given JSON string.
  45.     
  46.     :param string: the JSON string to decode
  47.     :type string: basestring
  48.     :return: the corresponding Python data structure
  49.     :rtype: object
  50.     """
  51.     if not _initialized:
  52.         _initialize()
  53.     return _decode(string)
  54.  
  55.  
  56. def encode(obj):
  57.     """Encode the given object as a JSON string.
  58.     
  59.     :param obj: the Python data structure to encode
  60.     :type obj: object
  61.     :return: the corresponding JSON string
  62.     :rtype: basestring
  63.     """
  64.     if not _initialized:
  65.         _initialize()
  66.     return _encode(obj)
  67.  
  68.  
  69. def use(module=None, decode=None, encode=None):
  70.     """Set the JSON library that should be used, either by specifying a known
  71.     module name, or by providing a decode and encode function.
  72.     
  73.     The modules "simplejson", "cjson", and "json" are currently supported for
  74.     the ``module`` parameter.
  75.     
  76.     If provided, the ``decode`` parameter must be a callable that accepts a
  77.     JSON string and returns a corresponding Python data structure. The
  78.     ``encode`` callable must accept a Python data structure and return the
  79.     corresponding JSON string. Exceptions raised by decoding and encoding
  80.     should be propagated up unaltered.
  81.     
  82.     :param module: the name of the JSON library module to use, or the module
  83.                    object itself
  84.     :type module: str or module
  85.     :param decode: a function for decoding JSON strings
  86.     :type decode: callable
  87.     :param encode: a function for encoding objects as JSON strings
  88.     :type encode: callable
  89.     """
  90.     global _decode, _encode, _initialized, _using
  91.     if module is not None:
  92.         if not isinstance(module, basestring):
  93.             module = module.__name__
  94.         if module not in ('cjson', 'json', 'simplejson'):
  95.             raise ValueError('Unsupported JSON module %s' % module)
  96.         _using = module
  97.         _initialized = False
  98.     else:
  99.         assert decode is not None and encode is not None
  100.         _using = 'custom'
  101.         _decode = decode
  102.         _encode = encode
  103.         _initialized = True
  104.  
  105.  
  106. def _initialize():
  107.     global _initialized
  108.  
  109.     def _init_simplejson():
  110.         global _decode, _encode
  111.         import simplejson
  112.         _decode = lambda string, loads=simplejson.loads: loads(string)
  113.         _encode = lambda obj, dumps=simplejson.dumps: \
  114.             dumps(obj, allow_nan=False, ensure_ascii=False)
  115.  
  116.     def _init_cjson():
  117.         global _decode, _encode
  118.         import cjson
  119.         _decode = lambda string, decode=cjson.decode: decode(string)
  120.         _encode = lambda obj, encode=cjson.encode: encode(obj)
  121.  
  122.     def _init_stdlib():
  123.         global _decode, _encode
  124.         json = __import__('json', {}, {})
  125.         print 'Using stdlib json'
  126.         _decode = lambda string, loads=json.loads: loads(string)
  127.         _encode = lambda obj, dumps=json.dumps: \
  128.             dumps(obj, allow_nan=False, ensure_ascii=False)
  129.  
  130.     if _using == 'simplejson':
  131.         _init_simplejson()
  132.     elif _using == 'cjson':
  133.         _init_cjson()
  134.     elif _using == 'json':
  135.         _init_stdlib()
  136.     elif _using != 'custom':
  137.         try:
  138.             _init_simplejson()
  139.         except ImportError:
  140.             _init_stdlib()
  141.     _initialized = True
  142.